from rpc_server.protobuf import Genes_pb2, Genes_pb2_grpc
import model.models as models
import model.sql as sql
import logging
import stock_service.Stocks as sto


def _execute(call):
    session = sql.DBSession()
    try:
        for data in call(session):
            yield data
    except Exception as e:
        logging.error('receive error', exc_info=e)
    finally:
        session.close()


class GenesService(Genes_pb2_grpc.GenesServiceServicer):

    def LoadAllGenes(self, request, context):
        for data in _execute(lambda session: session.query(models.genes)):
            yield Genes_pb2.GenesResp(**data)

    def LoadEverydayGeneNumber(self, request, context):
        for data in _execute(lambda session: session.query(models.genes_kl,
                                                           _filter=sql.Filter("code='%s'" % request.code),
                                                           orders=[sql.Order('date', asc=False)]
                                                           )):
            # 无法确定不存在哪个类？
            fields = Genes_pb2._GENENUMBERRESP.fields
            params = {}
            for field in fields:
                if field.name in data.keys():
                    params[field.name] = data[field.name]
            yield Genes_pb2.GeneNumberResp(**params)

    def RefreshGenes(self, request, context):
        try:
            sto.init_genes()
            return Genes_pb2.Status(status=True)
        except Exception as e:
            logging.error('error, ', exc_info=e)
            return Genes_pb2.Status(status=False)

    def RefreshGeneNumber(self, request, context):
        try:
            logging.info('refresh ---')
            sto.init_gene_kl(request.code, request.market)
            return Genes_pb2.Status(status=True)
        except Exception as e:
            logging.error('error, ', exc_info=e)
            return Genes_pb2.Status(status=False)
